package com.whj.wkpt.controller;

import com.whj.wkpt.entity.Task;
import com.whj.wkpt.entity.TaskReview;
import com.whj.wkpt.entity.User;
import com.whj.wkpt.service.TaskReviewService;
import com.whj.wkpt.service.TaskService;
import com.whj.wkpt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/task-reviews")
public class TaskReviewController {

    @Autowired
    private TaskReviewService taskReviewService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private UserService userService;

    // 提交任务评价页面
    @GetMapping("/create")
    public String createReviewForm(@RequestParam Long taskId, 
                                   @RequestParam(required = false) Long applicationId,
                                   Model model, Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);

        if (currentUser == null) {
            return "redirect:/login";
        }

        Task task = taskService.findById(taskId);
        if (task == null) {
            return "redirect:/employer/tasks";
        }

        // 检查用户是否有权限评价该任务（必须是任务的雇主）
        if (!task.getEmployerId().equals(currentUser.getUserId())) {
            return "redirect:/employer/tasks";
        }

        model.addAttribute("task", task);
        model.addAttribute("taskReview", new TaskReview());
        model.addAttribute("applicationId", applicationId);
        return "employer/review-form";
    }

    // 提交任务评价
    @PostMapping
    public String createReview(@ModelAttribute TaskReview taskReview, 
                               @RequestParam Long taskId,
                               @RequestParam(required = false) Long applicationId,
                               Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);

        if (currentUser == null) {
            return "redirect:/login";
        }

        Task task = taskService.findById(taskId);
        if (task == null) {
            return "redirect:/employer/tasks";
        }

        // 检查用户是否有权限评价该任务（必须是任务的雇主）
        if (!task.getEmployerId().equals(currentUser.getUserId())) {
            return "redirect:/employer/tasks";
        }

        // 设置评价信息
        taskReview.setTaskId(taskId);
        taskReview.setEmployerId(currentUser.getUserId());
        
        // 获取承接该任务的威客ID
        // 在实际应用中，应该从任务申请记录中获取承接该任务的威客
        // 这里为了简化，我们假设任务已完成，从已有的评价中查找对应的威客
        List<TaskReview> existingReviews = taskReviewService.findByTaskId(taskId);
        if (!existingReviews.isEmpty()) {
            // 如果已存在评价，使用第一个评价中的威客ID
            taskReview.setFreelancerId(existingReviews.get(0).getFreelancerId());
        } else {
            // 如果没有评价记录，暂时使用一个默认的威客ID（实际应用中应该从任务申请记录中获取）
            List<User> freelancers = userService.findAllUsers().stream()
                    .filter(user -> "freelancer".equals(user.getRole()))
                    .toList();
            if (!freelancers.isEmpty()) {
                taskReview.setFreelancerId(freelancers.get(0).getUserId());
            }
        }

        taskReviewService.createReview(taskReview);
        
        // 如果提供了applicationId，则跳转回任务承接详情页面，否则跳转到任务列表
        if (applicationId != null) {
            return "redirect:/employer/task-applications/" + applicationId;
        } else {
            return "redirect:/employer/tasks";
        }
    }

    // 修改任务评价页面
    @GetMapping("/edit/{reviewId}")
    public String editReviewForm(@PathVariable Long reviewId, 
                                 @RequestParam(required = false) Long applicationId,
                                 Model model, Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);

        if (currentUser == null) {
            return "redirect:/login";
        }

        TaskReview taskReview = taskReviewService.findById(reviewId);
        if (taskReview == null) {
            return "redirect:/employer/tasks";
        }

        // 检查用户是否有权限修改该评价（必须是评价的雇主）
        if (!taskReview.getEmployerId().equals(currentUser.getUserId())) {
            return "redirect:/employer/tasks";
        }

        Task task = taskService.findById(taskReview.getTaskId());
        model.addAttribute("task", task);
        model.addAttribute("taskReview", taskReview);
        model.addAttribute("applicationId", applicationId);
        return "employer/review-form";
    }

    // 修改任务评价
    @PostMapping("/update/{reviewId}")
    public String updateReview(@PathVariable Long reviewId, 
                               @ModelAttribute TaskReview taskReview,
                               @RequestParam(required = false) Long applicationId,
                               Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);

        if (currentUser == null) {
            return "redirect:/login";
        }

        TaskReview existingReview = taskReviewService.findById(reviewId);
        if (existingReview == null) {
            return "redirect:/employer/tasks";
        }

        // 检查用户是否有权限修改该评价（必须是评价的雇主）
        if (!existingReview.getEmployerId().equals(currentUser.getUserId())) {
            return "redirect:/employer/tasks";
        }

        // 更新评价信息
        existingReview.setContent(taskReview.getContent());
        existingReview.setRating(taskReview.getRating());
        taskReviewService.updateReview(existingReview);

        // 如果提供了applicationId，则跳转回任务承接详情页面，否则跳转到任务列表
        if (applicationId != null) {
            return "redirect:/employer/task-applications/" + applicationId;
        } else {
            return "redirect:/employer/tasks";
        }
    }

    // 删除任务评价
    @PostMapping("/delete/{reviewId}")
    public String deleteReview(@PathVariable Long reviewId, 
                               @RequestParam(required = false) Long applicationId,
                               Authentication authentication) {
        String username = authentication.getName();
        User currentUser = userService.findByUsername(username).orElse(null);

        if (currentUser == null) {
            return "redirect:/login";
        }

        TaskReview taskReview = taskReviewService.findById(reviewId);
        if (taskReview == null) {
            return "redirect:/employer/tasks";
        }

        // 检查用户是否有权限删除该评价（必须是评价的雇主）
        if (!taskReview.getEmployerId().equals(currentUser.getUserId())) {
            return "redirect:/employer/tasks";
        }

        taskReviewService.deleteReview(reviewId);
        
        // 如果提供了applicationId，则跳转回任务承接详情页面，否则跳转到任务列表
        if (applicationId != null) {
            return "redirect:/employer/task-applications/" + applicationId;
        } else {
            return "redirect:/employer/tasks";
        }
    }

    // 查询任务评价（按任务ID）
    @GetMapping("/task/{taskId}")
    public String getReviewsByTask(@PathVariable Long taskId, Model model) {
        List<TaskReview> reviews = taskReviewService.findByTaskId(taskId);
        Task task = taskService.findById(taskId);
        
        model.addAttribute("reviews", reviews);
        model.addAttribute("task", task);
        return "employer/reviews";
    }
    
    // 按评价时间查询评价（简化实现）
    @GetMapping
    public String searchReviews(@RequestParam(required = false) Long taskId,
                                @RequestParam(required = false) String reviewTime,
                                Model model) {
        List<TaskReview> reviews;
        if (taskId != null) {
            reviews = taskReviewService.findByTaskId(taskId);
        } else {
            reviews = taskReviewService.findAll();
        }
        
        model.addAttribute("reviews", reviews);
        return "employer/reviews";
    }
}